package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
	
	public class Server {
		
	// maps usernames to User class
	public static Map<String, User> userMap = new HashMap<String, User>();	
	
	// maps usernames to appropriate writer
	public static Map<String, PrintWriter> clientWriters = new HashMap<String, PrintWriter>();
	
	// one global chatroom for all users
	public static Chatroom chatroom = new Chatroom(); 
	
	// maps stackID to user name
	public static Map<String, String> stackUserMap = new HashMap<String, String>();

	public static void main(String[] args) {
    	
		// Create a socket server that listens on port 4444 in the local
		// machine.
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(4444);
		} catch (IOException e) {
			System.err.println("Could not listen on port: 4444.");
			System.exit(1);
		}
		
        ServerManager servermanager = new ServerManager();
		Thread serverThread = new Thread(servermanager);
        serverThread.start();
        
		try {
			
			while (true) {
				
				// Wait until someone connects.
				System.out.println("Accepting connections...");
				Socket socket = serverSocket.accept();

				BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
				
				// create new controller thread for each user
				System.out.println("Client connection made");
		        ClientController controller = new ClientController(reader, writer);
		        Thread clientThread = new Thread(controller);
		        System.out.println("starting client controller thread");
		        clientThread.start();

			}
			
		} 
		catch (IOException e) 
		{
			System.err.println("Accept failed.");
			System.exit(1);
		}
    }    
	
	
}
